import effectRunnerMap from './effectRunnerMap';
import { IO } from './symbols';

export default function proc(env, iterator) {
  next();

  function next(arg, isErr) {
    let result;
    if (isErr) {
      result = iterator.throw(arg);
    } else {
      result = iterator.next(arg);
    }

    // result 结构：{ value:xxx, done:true/false }
    if (!result.done) {
      // 处理 生成器执行后 返回的 Effect 对象
      digestEffect(result.value, next);
    }
  }

  function runEffect(effect, currCb) {
    if (effect && effect[IO]) {
      const effectRunner = effectRunnerMap[effect.type];
      effectRunner(env, effect.payload, currCb);
    } else {
      currCb();
    }
  }

  function digestEffect(effect, cb) {
    let effectSettled; // 一个标记 表示是否变更

    function currCb(res, isErr) {
      if (effectSettled) return; // 变更了就不管了，没变更就执行下面的函数
      effectSettled = true;
      cb(res, isErr);
    }

    runEffect(effect, currCb);
  }
}
